package mil.af.amc.adpetracker.web.actions.struts1.EquipmentType;

import mil.af.amc.adpetracker.model.EquipmentType;
import mil.af.amc.adpetracker.model.Manufacturer;
import mil.af.amc.adpetracker.service.EquipmentTypeService;
import mil.af.amc.adpetracker.service.ItemModelService;
import mil.af.amc.adpetracker.service.ManufacturerService;
import mil.af.amc.adpetracker.web.actions.struts1.AbstractAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class GetEquipmentTypeByManufacturerAction extends AbstractAction {

    private ManufacturerService manufacturerService;

    public void setManufacturerService(ManufacturerService manufacturerService) {
        this.manufacturerService = manufacturerService;
    }

    private ItemModelService itemModelService;

    public void setItemModelService(ItemModelService itemModelService) {
        this.itemModelService = itemModelService;
    }

    private EquipmentTypeService equipmentTypeService;

    public void setEquipmentTypeService(EquipmentTypeService equipmentTypeService) {
        this.equipmentTypeService = equipmentTypeService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        Integer manufacturerId;

        // KLUDGE ALERT! From now on the interface for my model objects will have "id" and "name", I promise!
        if (httpServletRequest.getParameter("manufacturerId") != null) {
            manufacturerId = Integer.parseInt(httpServletRequest.getParameter("manufacturerId"));
        } else {
            manufacturerId = Integer.parseInt(httpServletRequest.getParameter("id"));
        }

        Manufacturer manufacturer = manufacturerService.getById(manufacturerId);
        httpServletRequest.getSession().setAttribute("manufacturer", manufacturer);

        List<EquipmentType> results = equipmentTypeService.getByManufacturer(manufacturerId);
        Collections.sort(results);

        JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(results);
        httpServletResponse.setHeader("Content-Type", "application/json");
        httpServletResponse.getWriter().println(jsonArray);

        return null;
    }

}
